package com.ymatou.iapi.liveseller.testcase;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.experimental.categories.Category;

import com.ymatou.iapi.liveseller.parameter.ActivityCatalogDetailsDto;
import com.ymatou.iapi.liveseller.parameter.ActivityProductDetailsDto;
import com.ymatou.iapi.liveseller.parameter.CreateLiveActivityBean;
import com.ymatou.iapi.liveseller.parameter.CreateSellerLiveBean;
import com.ymatou.iapi.liveseller.parameter.LiveActivityDetailsBean;
import com.ymatou.iapi.liveseller.service.LiveActivityDetailsCall;
import com.ymatou.iapi.productmanager.parameter.product.AddSellerProductRequest;
import com.ymt.core.tool.Logger;
import com.ymt.utils.annotation.*;
import com.ymt.utils.tag.*;
import com.ymttest.business.service.LiveRoomCallService;
import com.ymttest.business.service.ProductManagerCallServiceV2;
import com.ymttest.database.model.LiveActivity;
import com.ymttest.database.model.LiveActivityProduct;
import com.ymttest.database.model.LiveRoom;
import com.ymttest.database.model.YmtCatalogsI;
import com.ymttest.database.model.YmtProductActivityStock;
import com.ymttest.database.mongo.jproduct.CatalogsWapper;
import com.ymttest.database.mongo.jproduct.ProductsWapperV2;
import com.ymttest.database.sqlwapper.LiveRoomWapper;
import com.ymttest.database.sqlwapper.YmtCatalogsIWapper;
import com.ymttest.database.sqlwapper.YmtProductActivityStockWapper;
import com.ymttest.utils.EnvSetup;
import com.ymttest.utils.YMTDateUtil;

/**
 * 活动详情 FreeMaker Template自动生成代码
 */
@TestSuite
public class Ts_LiveActivityDetails {
	private static LiveActivityDetailsBean liveactivitydetailsBean;
	private static LiveActivityDetailsCall liveactivitydetailsCall;
	private static int sellerId = Integer.parseInt(EnvSetup.getData("autotest_seller1"));

	@BeforeClass
	public static void setUp() {
		Logger.createResultFile("活动详情");
	}

	@Before
	public void caseUp() {
		liveactivitydetailsBean = new LiveActivityDetailsBean();
		liveactivitydetailsCall = new LiveActivityDetailsCall();
	}

	@AfterClass
	public static void tearDown() {
		Logger.generateResult(liveactivitydetailsCall.getOpurl());
	}

	@After
	public void caseDown() {
		Logger.end();
	}

	@Test
	@Category({ P1.class })
	@TestCase
	public void Tc_LiveActivityDetails_001() {
		Logger.start(true, "使用userid和productids查询活动详情,成功");
		try {
			// productids 查到的是创建商品时候的信息,活动无关
			Logger.comment("创建商品");
			AddSellerProductRequest addpro = ProductManagerCallServiceV2.initAddSellerProductRequest(sellerId);
			String productId = ProductManagerCallServiceV2.addNewProduct(addpro).get("Data").getAsJsonObject().get("ProductId").getAsString();
			Logger.comment("创建直播");
			// 5分钟后开始200分钟后结束
			CreateSellerLiveBean clive = LiveRoomCallService.initCreatesellerliveBean(sellerId);
			Date now = YMTDateUtil.getDate();
			// 半小时之内会锁定不能修改
			Date starttime = new Date(now.getTime() + 60 * 60 * 1000);
			Date endtime = new Date(now.getTime() + 200 * 60 * 1000);
			clive.getLiveDto().setStartTime(YMTDateUtil.getFormatTime(starttime, YMTDateUtil.YMDHMS));
			
			LiveRoom createlive = LiveRoomCallService.CreateSellerLive(clive);
			Logger.comment("加入商品");
			LiveRoomCallService.AddProductsToLive(createlive.getId(), sellerId, productId);
			Logger.comment("查询商品规格");
			YmtCatalogsIWapper CIWapper = new YmtCatalogsIWapper();
			List<String> cids = CIWapper.selectCatalogsByProductId(productId).stream().map(YmtCatalogsI::getsCatalogId).collect(Collectors.toList());
			Logger.comment("创建秒杀活动");
			CreateLiveActivityBean createliveactivityBean = LiveRoomCallService.initCreateLiveActivityBean(createlive.getId(), cids.get(0), 5d, 6, starttime);
			LiveRoomCallService.CreateLiveActivity(createliveactivityBean);

			List<String> ProductIds = new ArrayList<>();
			ProductIds.add(productId);
			liveactivitydetailsBean.setUserId(sellerId);
			liveactivitydetailsBean.setProductIds(ProductIds);
			liveactivitydetailsCall.setData(liveactivitydetailsBean);
			liveactivitydetailsCall.callService();
			Logger.verifyEquals("200", liveactivitydetailsCall.getString("Code"), "验证Code");
			verifyDB(productId, addpro);
		} catch (Exception e) {
			Logger.fail(e);
		}
	}

	@Test
	@Category({ P2.class })
	@TestCase
	public void Tc_LiveActivityDetails_002() {
		Logger.start(true, "不传参数失败");
		try {
			liveactivitydetailsCall.setData(liveactivitydetailsBean);
			liveactivitydetailsCall.callService();
			Logger.verifyEquals("400", liveactivitydetailsCall.getString("Code"), "验证Code");
		} catch (Exception e) {
			Logger.fail(e);
		}
	}

	@Test
	@Category({ P2.class })
	@TestCase
	public void Tc_LiveActivityDetails_003() {
		Logger.start(true, "使用LiveActivityId和userid查询活动详情,成功");
		try {
			Logger.comment("创建商品");
			AddSellerProductRequest addpro = ProductManagerCallServiceV2.initAddSellerProductRequest(sellerId);
			String productId = ProductManagerCallServiceV2.addNewProduct(addpro).get("Data").getAsJsonObject().get("ProductId").getAsString();
			Logger.comment("创建直播");
			// 5分钟后开始200分钟后结束
			CreateSellerLiveBean clive = LiveRoomCallService.initCreatesellerliveBean(sellerId);
			Date now = YMTDateUtil.getDate();
			// 半小时之内会锁定不能修改
			Date starttime = new Date(now.getTime() + 60 * 60 * 1000);
			Date endtime = new Date(now.getTime() + 200 * 60 * 1000);
			clive.getLiveDto().setStartTime(YMTDateUtil.getFormatTime(starttime, YMTDateUtil.YMDHMS));
			
			LiveRoom createlive = LiveRoomCallService.CreateSellerLive(clive);
			Logger.comment("加入商品");
			LiveRoomCallService.AddProductsToLive(createlive.getId(), sellerId, productId);
			Logger.comment("查询商品规格");
			YmtCatalogsIWapper CIWapper = new YmtCatalogsIWapper();
			List<String> cids = CIWapper.selectCatalogsByProductId(productId).stream().map(YmtCatalogsI::getsCatalogId).collect(Collectors.toList());
			Logger.comment("创建秒杀活动");
			CreateLiveActivityBean createliveactivityBean = LiveRoomCallService.initCreateLiveActivityBean(createlive.getId(), cids.get(0), 5d, 6, starttime);
			LiveRoomCallService.CreateLiveActivity(createliveactivityBean);
			LiveRoomWapper LiveRoomWapper = new LiveRoomWapper();
			Integer LiveActivityId = LiveRoomWapper.selectLiveactivityByLiveId(createliveactivityBean.getLiveActivity().getLiveId()).get(0).getLiveActivityId();
			liveactivitydetailsBean.setUserId(sellerId);
			liveactivitydetailsBean.setLiveActivityId(LiveActivityId);
			liveactivitydetailsCall.setData(liveactivitydetailsBean);
			liveactivitydetailsCall.callService();
			Logger.verifyEquals("200", liveactivitydetailsCall.getString("Code"), "验证Code");
			verifyDB(productId, addpro);
		} catch (Exception e) {
			Logger.fail(e);
		}
	}

	private void verifyDB(String productid, AddSellerProductRequest addpro) throws Exception {
		Logger.comment("开始校验商品信息Products");
		List<String> productIds = liveactivitydetailsBean.getProductIds();
		LiveRoomWapper LiveRoomWapper = new LiveRoomWapper();
		CatalogsWapper CatalogsWapper = new CatalogsWapper();
		YmtProductActivityStockWapper YmtProductActivityStockWapper = new YmtProductActivityStockWapper();
		LiveActivity liveacctivity = null;
		List<LiveActivityProduct> livep = null;
		if (productIds == null || productIds.isEmpty()) {
			if (liveactivitydetailsBean.getLiveActivityId() != null && liveactivitydetailsBean.getLiveActivityId() > 0) {
				liveacctivity = LiveRoomWapper.selectLiveactivityById(liveactivitydetailsBean.getLiveActivityId());
				livep = LiveRoomWapper.selectLiveactivityproduct(liveactivitydetailsBean.getLiveActivityId(), productid);
			}
		}
		Map<String, Object> productMap = new ProductsWapperV2().getByProductId(productid);
		Logger.debug(productMap);
		if (liveacctivity != null) {
			// StartTime":1532598770857,"EndTime":1532598890857
			Logger.verifyEquals(true,Math.abs(liveactivitydetailsCall.getData().getStartTime()-liveacctivity.getStartTime().getTime())<2*1000, "验证StartTime成功");
			Logger.verifyEquals(true,Math.abs(liveactivitydetailsCall.getData().getEndTime()-liveacctivity.getEndTime().getTime())<2*1000, "验证EndTime成功");
			
		}

		List<ActivityProductDetailsDto> aps = liveactivitydetailsCall.getData().getActivityProducts();
		aps.forEach(ap -> {

			Logger.verifyEquals(productid, ap.getProductId(), "验证productid");
			Logger.verifyEquals(addpro.getProduct().getProductName(), ap.getProductName(), "验证ProductName");
			Logger.verifyEquals(addpro.getProduct().getProductPicList().get(0), ap.getMainPic(), "验证MainPic");
			List<ActivityCatalogDetailsDto> catalog = ap.getActivityCatalogs();
			catalog.forEach(cata -> {
				String cid = cata.getCatalogId();
				try {
					Map<String, Object> mc = CatalogsWapper.getByCatalogId(cid);
					// mc:{_id=5b599af78a0ceb4d6c5664d8, newp=10.0,
					// package=false, mflight=0.0,
					// spid=ebb869d2-6c1c-4fe2-87ce-640caab60b64, presale=false,
					// sid=24635724, props=[ { "name" : "颜色" , "value" : "红色" ,
					// "pic" :
					// "http://s2.ymatou.com/home/b5abefb15e5afbb91d82c65df819be22.png"}],
					// price=10.0, earnest=0.0, mdeliv=0, vip=10.0,
					// stock=999994,
					// sku=sku-7232f1de-ffbf-49ae-a0bc-d8765456b07f, wt=0.0,
					// cid=9b998a9f-c9aa-469e-af8e-cc390be0d7a1}
					Logger.verifyEquals(mc.get("stock"), cata.getStock(), "验证stock");
					Logger.verifyEquals(mc.get("price"), cata.getPrice(), "验证price");
					Logger.verifyEquals(((List<Map>) mc.get("props")).get(0).get("value"), cata.getAttributeName(), "验证AttributeName");
					//这里待确定,出现了cid验证后为null的情况
					List<YmtProductActivityStock> list = YmtProductActivityStockWapper.selectByProductId(productid).stream().filter(ypas -> {
						return ypas.getScatalogid().equals(cid);
					}).filter(ypas -> {
						return ypas.getfActivityPrice() != null;
					}).collect(Collectors.toList());
					
					if (list != null && list.size() > 0&&liveactivitydetailsBean.getProductIds()==null) {
						YmtProductActivityStock ymtProductActivityStock = list.get(0);
						Logger.verifyEquals(ymtProductActivityStock.getfActivityPrice(), cata.getActivityPrice(), "验证ActivityPrice");
						Logger.verifyEquals(ymtProductActivityStock.getIstocknum(), cata.getActivityStock(), "验证ActivityStock");
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			});
		});
	}
}